package model.utils;

/**
 * 工具类
 * 用于计算输入的字符串的宽度和高度
 */
public class StringWidthAndHeightUtil {

    //宽
    public static double getWidth(String str, double maxWidth) {
        int len = str.length();
        double width = 16;
        String[] lines = str.split("\n");
        double maxs = 0;
        for (int i=0; i<lines.length; i++) {
            for (int j=0; j<lines[i].length(); j++) {
                if (isChinese(str.charAt(i))) {
                    width += 17;
                } else {
                    width += 9;
                }
            }
            if (maxs <= width) {
                maxs = width;
            }
            width = 16;
        }

        if (maxs <= maxWidth) {
            return maxs;
        } else {
            return maxWidth;
        }

        //29中 17=15px/64英 8=7px
//        for (int i=0; i<len; i++) {
//            if (isChinese(str.charAt(i))) {
//                width += 17;
//            } else {
//                width += 9;
//            }
//        }

//        if (width <= maxWidth) {
//            return width+8;
//        } else {
//            return maxWidth;
//        }
    }

    //高
    public static double getHeight(String str, double maxWidth) {
        double width = 16;
        double height = 40;
        for (int i=0; i<str.length(); i++) {
            if (str.charAt(i) == '\n') {
                width += maxWidth;
            }
            if (isChinese(str.charAt(i))) {
                width += 17;
            } else {
                width += 9;
            }
            if (width >= maxWidth) {
                width = 20;
//                height += 17.4;
                height += 18;
            }
        }
        return height + 5;
    }

    /**
     * 判断字符是否是中文
     * @param ch
     * @return
     */
    private static final boolean isChinese(char ch) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(ch);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;
    }
}
